package com.kingbull.recorder.slice;

import com.kingbull.recorder.ResourceTable;
import com.kingbull.recorder.adapter.TextAdapter;
import com.kingbull.recorder.utils.MyToast;
import com.kingbull.recorder.utils.PermissionUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;
import java.util.Arrays;

/**
 * MainAbilitySlice
 */
public class MainAbilitySlice extends AbilitySlice {
    private final String[] demoArray = new String[]{"Pcm Recorder", "Wav Recorder"};

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        Text text = (Text) findComponentById(ResourceTable.Id_text_title);
        text.setText(getString(ResourceTable.String_entry_MainAbility));
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_listview);
        listContainer.setItemProvider(new TextAdapter(this, Arrays.asList(demoArray)));
        listContainer.setItemClickedListener((listContainer1, component, position, l) -> {
            String[] permissions = new String[]{
                    "ohos.permission.WRITE_USER_STORAGE",
                    "ohos.permission.READ_USER_STORAGE",
                    "ohos.permission.MICROPHONE",
            };
            boolean flag = PermissionUtils.hasPermissions(getAbility(), permissions);
            if (!flag) {
                try {
                    MyToast.show2(getContext(), getResourceManager().getElement(ResourceTable.String_no_permission).getString());
                } catch (IOException | NotExistException | WrongTypeException e) {
                    e.printStackTrace();
                }
                return;
            }
            switch (position) {
                case 0:
                    present(new PcmRecorderAbilitySlice(), new Intent());
                    break;
                case 1:
                    present(new WavRecorderAbilitySlice(), new Intent());
                    break;
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
